#include<iostream>
#include<unistd.h>
#include<string>
#include<sys/wait.h>
using namespace std;

int main()
{
    int fds[2]={0};
    int n = pipe(fds);
    pid_t id = fork();
    if(id < 0)
    {
        cerr<<"fork fail"<<endl;
    }
    else if(id == 0)
    {
        //子进程,只写不读
        close(fds[0]);
        int cnt = 0;
        while(1)
        {
            string message = "hello ";
            message += to_string(getpid());
            message += ",";
            message += to_string(cnt);

            ::write(fds[1], message.c_str(), message.size());
            cnt++;
            sleep(1);
        }
        exit(0);

    }
    else{
        //father,只读不写
        close(fds[1]);
        char buffer[1024];
        while(1)
        {
            ssize_t n = ::read(fds[0], buffer, 1024);
            if(n > 0)
                buffer[n] = 0;

            cout<<"child->father,message:"<<buffer<<endl;
        }

        pid_t rid = waitpid(id,nullptr,0);
        cout<<"father process succeed:"<<rid<<endl;
        
    }
    return 0;
}
